package com.test.mooan.labama.activity_fragment_boom.process_boom;

import static com.test.mooan.labama.utils_boom.Permissionutil_boom.Permission_Code_Camera;

import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageButton;

import androidx.annotation.NonNull;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.exifinterface.media.ExifInterface;

import com.test.mooan.labama.constants_boom.Constant_boom;
import com.google.common.util.concurrent.ListenableFuture;
import com.test.mooan.labama.R;
import com.test.mooan.labama.activity_fragment_boom.base_boom.BaseApplication_boom;
import com.test.mooan.labama.activity_fragment_boom.base_boom.BaseInfoActivity_boom;
import com.test.mooan.labama.bean_boom.config_info_boom.UrlInfo_boom;
import com.test.mooan.labama.utils_boom.Permissionutil_boom;
import com.test.mooan.labama.utils_boom.Threadutils_boom;
import com.test.mooan.labama.utils_boom.helper_boom.UserInfoHelper_boom;
import com.test.mooan.labama.utils_boom.http_boom.HttpManager_boom;
import com.test.mooan.labama.utils_boom.imageUtil_boom.ImageConvert_boom;
import com.test.mooan.labama.view_boom.widget_boom.TitleView_boom;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.TreeMap;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class FaceUploadActivity_boom extends BaseInfoActivity_boom implements EasyPermissions.PermissionCallbacks,EasyPermissions.RationaleCallbacks{

    private PreviewView imagePv;
    private ImageButton imageIb;
    private ImageButton photographIb;

    private Bitmap imageBitmap;
    private String imageUrl;

    private CheckBox deleteDataCb;

    private ListenableFuture<ProcessCameraProvider> processCameraProviderListenableFuture;
    private ImageCapture imageCapture;

    private boolean startTakingFlag = true;

    private String imgPath = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_upld_boom);
        init();
    }

    private void init() {
        TitleView_boom titleView = findViewById(R.id.activity_face_upload_view_title);
        setBackBtn_boom(titleView.getBackIb());

        imagePv = findViewById(R.id.activity_face_upload_pv_image);
        imageIb = findViewById(R.id.activity_face_upload_ib_image);
        photographIb = findViewById(R.id.afu_ib_photograph);

        deleteDataCb = findViewById(R.id.activity_face_upload_pv_cb_delete_data);

        //下一步按键点击
        findViewById(R.id.activity_face_upload_btn_next).setOnClickListener(v -> {
            HttpManager_boom.getInstance().saveUserPointForBatch();
            runWithCameraPermission(() -> {

                if (TextUtils.isEmpty(imageUrl)) startPhotograph();//没有照片时自动开启拍照
                else {
                    UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_SAVE_CLICK").toUpperCase());
                    UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_USE_PHOTO_CLICK").toUpperCase());
                    HttpManager_boom.getInstance().uploadInfo(UrlInfo_boom.gInstance().gCyk3(), new TreeMap<String, String>() {{
                        put("faceImgUrl", imageUrl);
                        put("deleteDataFlag", deleteDataCb.isChecked() ? "YES" : "NO");
                    }});
                }
            });
        });

        //开始人脸拍照点击
        imageIb.setOnClickListener(v -> runWithCameraPermission(this::startPhotograph));

        //拍照点击
        photographIb.setOnClickListener(v ->
                runWithCameraPermission(() -> {
                if (!TextUtils.isEmpty(imageUrl)) startPhotograph();
                else captureImage();
            })
        );

    }

    private void startPhotograph(){

        if (startTakingFlag) {
            UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_START_TAKING_CLICK").toUpperCase());
            startTakingFlag = false;
        }else UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_REMAKE_CLICK").toUpperCase());

        imageUrl = "";

        //打开拍照
        processCameraProviderListenableFuture = ProcessCameraProvider.getInstance(this);
        //监听摄像头的启动
        processCameraProviderListenableFuture.addListener(() -> {
            try {
                ProcessCameraProvider provider = processCameraProviderListenableFuture.get();

                imagePv.setVisibility(View.VISIBLE);

                //释放资源
                provider.unbindAll();

                //创建相机选择器并选择前置摄像头
                CameraSelector cameraSelector = new CameraSelector.Builder()
                        .requireLensFacing(CameraSelector.LENS_FACING_FRONT)
                        .build();

                //创建一个相机预览对象并将其与PreviewView的SurfaceProvider绑定，实现在该组件上显示相机预览画面
                Preview preview = new Preview.Builder().build();
                preview.setSurfaceProvider(imagePv.getSurfaceProvider());

                //创建一个ImageCapture对象用于拍摄照片，设置拍照模式为最小化延迟模式
                imageCapture = new ImageCapture.Builder()
                        .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
                        .build();

                //点击图像隐藏,拍照按键显示
                imageIb.setImageBitmap(null);
                photographIb.setVisibility(View.VISIBLE);

                //启动相机并将其与当前生命周期绑定  cameraSelector用于选择相机设备，preview用于显示预览。imageCapture用于捕获图像
                provider.bindToLifecycle(this, cameraSelector, preview, imageCapture);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }, ContextCompat.getMainExecutor(this));
    }

    //拍照
    private void captureImage() {

        UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_TAKE_PICTURE_CLICK").toUpperCase());

        imgPath = this.getImageFilePath();
        ImageCapture.OutputFileOptions options = new ImageCapture.OutputFileOptions.Builder(new File(imgPath)).build();
        imageCapture.takePicture(
            //指定照片保存的位置和格式
            options,
            //指定保存照片时要运行的线程
            ContextCompat.getMainExecutor(this),
            //指定保存照片完成后的回调函数
            new ImageCapture.OnImageSavedCallback() {
                @Override
                public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                    try {
                        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
                        imageBitmap = rotateBitmap(bitmap, imgPath);

                        if (!TextUtils.isEmpty(imgPath)) {
                            //照片压缩
                            ImageConvert_boom.startConvertImage(
                                    new File(imgPath),
                                    (localPath, thumpImg) -> {
                                        imageBitmap = thumpImg;
                                        //上传照片
                                        Threadutils_boom.getInstance().runOnChildThread(() -> HttpManager_boom.getInstance().uploadImage(localPath));
                                    }
                            );
                        } else {
                            imageUrl = null;
                            showToast_boom(getString(R.string.photo_upload_again_tip));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                @Override
                public void onError(@NonNull ImageCaptureException exception) {
                    showToast_boom("Error: " + exception.getMessage());
                }
            }
        );

    }

    public void onPhotoUploadResponse(String imageUrl) {
        if (TextUtils.isEmpty(imageUrl)) {
            showToast_boom(getString(R.string.photo_upload_again_tip));
            return;
        }

        this.imageUrl = imageUrl;

        imageIb.setImageBitmap(imageBitmap);
        imagePv.setVisibility(View.GONE);
    }

    /**
     * 根据角度反转图片
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, String imageFilePath) {
        try {
            ExifInterface exif = new ExifInterface(imageFilePath);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
            Matrix matrix = new Matrix();

            switch (orientation) {
                case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                    matrix.setScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    matrix.setRotate(180);
                    break;
                case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                    matrix.setRotate(180);
                    matrix.postScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_TRANSPOSE:
                    matrix.setRotate(90);
                    matrix.postScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    matrix.setRotate(90);
                    break;
                case ExifInterface.ORIENTATION_TRANSVERSE:
                    matrix.setRotate(-90);
                    matrix.postScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    matrix.setRotate(180);
                    break;
                default:
                    return bitmap;
            }

            try {
                Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                bitmap.recycle();
                return rotatedBitmap;
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 获取图片路径
     */
    private String getImageFilePath() {
        String pictureId = System.currentTimeMillis() + "";
        String imgDir = getSandboxFolderPath();
        return (imgDir + File.separator + pictureId + ".jpg");
    }

    /**
     * 获取沙盒路径
     */
    private String getSandboxFolderPath() {
        String inAppFolder = BaseApplication_boom.getInstant_boom().getFilesDir().getAbsolutePath();
        inAppFolder += File.separator;
        inAppFolder += Constant_boom.PRODUCT;
        inAppFolder += "_PICS";

        File folderFile = new File(inAppFolder);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        return inAppFolder;
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        switch (requestCode) {
            case Permission_Code_Camera:
                if (EasyPermissions.somePermissionPermanentlyDenied(this, perms))
                    new AppSettingsDialog.Builder(this).build().show();
                break;
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {}

    @Override
    public void onRationaleDenied(int requestCode) {}

    @Override
    public void onRationaleAccepted(int requestCode) {
        switch (requestCode) {
            case Permission_Code_Camera:
                EasyPermissions.requestPermissions(this,
                        "App requires camera permission.",
                        Permission_Code_Camera,
                        Manifest.permission.CAMERA);
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


//    /**
//     * 横向反转图片
//     */
//    private Bitmap matrixToX(Bitmap bitmap) {
//        Matrix matrix = new Matrix();
//        matrix.preScale(-1.0f, 1.0f);
//        Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
//        bitmap.recycle();
//        return result;
//    }

}